#include "client.h"

int transferFile(int sockfd, const char* filename)
{
    if(strlen(filename) == 0){
        printf("文件名为空\n");
        const char* errorinfo = "error";
        int len = strlen(errorinfo);
        sendn(sockfd, &len, sizeof(int));
        sendn(sockfd, errorinfo, len);
        return 0;
    }
    train_info file;
    memset(&file, 0, sizeof(file));
    file.len = strlen(filename);
    strcpy(file.buff, filename);
    sendn(sockfd, &file, sizeof(int)+file.len);
    int fd = open(filename, O_RDONLY);
    ERROR_CHECK(fd, -1, "open");

    struct stat fileInfo;
    memset(&fileInfo, 0, sizeof(struct stat));
    fstat(fd, &fileInfo);
    off_t lenth = fileInfo.st_size;
    sendn(sockfd, &lenth, sizeof(off_t));

    off_t cur = 0;
    int ret = 0;
    while(1){
        memset(&file, 0, sizeof(file));
        file.len= read(fd, file.buff,  sizeof(file.buff));
        ret = sendn(sockfd, &file, sizeof(int)+file.len);
        cur += (ret - 4);
        if(ret < 1000){
            break;
        }
        
    }
    printf("send %ld bytes.\n", cur);
    close(fd);
    return 0;
}

